package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.RejectReasonMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.RejectReason;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AuditWorkReqDto;
import com.jzo2o.customer.model.dto.request.WorkerCertificationInfoDTO;
import com.jzo2o.customer.model.dto.response.CertificationInfoDTO;
import com.jzo2o.customer.model.page.CertificationQueryPageParams;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RejectReasonMapper rejectReasonMapper;

    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    @Override
    public void add(WorkerCertificationInfoDTO workerCertificationInfoDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long id = currentUser.getId();
        //根据id查询数据库 有数据就是更新操作没有数据就是新增操作
        WorkerCertification one = getById(id);
        if (one != null) {
            //更新
            WorkerCertification bean = BeanUtil.toBean(workerCertificationInfoDTO, WorkerCertification.class);
            bean.setId(id);
            bean.setCertificationTime(null);
            bean.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
            boolean updateById = updateById(bean);
            if (!updateById) {
                throw new RuntimeException("更新认证信息失败");
            }
            //创建拒绝原因表
            RejectReason rejectReason = BeanUtil.toBean(bean, RejectReason.class);
            //清除id属性
            rejectReason.setId(null);
            //设置服务人员id
            rejectReason.setWorkInstitutionId(id);
            rejectReasonMapper.insert(rejectReason);
            return;
        }
        WorkerCertification workerCertification = BeanUtil.toBean(workerCertificationInfoDTO, WorkerCertification.class);
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        //设置服务人员id
        workerCertification.setId(id);
        boolean save = save(workerCertification);
        //创建拒绝原因表
        RejectReason rejectReason = BeanUtil.toBean(workerCertification, RejectReason.class);
        //清除id属性
        rejectReason.setId(null);
        //设置服务人员id
        rejectReason.setWorkInstitutionId(id);
        rejectReasonMapper.insert(rejectReason);
        if (!save) {
            throw new RuntimeException("申请认证失败请重新申请");
        }
    }

    @Override
    public PageResult<CertificationInfoDTO> pageQueryAgency(CertificationQueryPageParams certificationQueryPageParams) {
        PageResult<CertificationInfoDTO> page = PageHelperUtils.selectPage(certificationQueryPageParams, () -> rejectReasonMapper.queryWorkerList(certificationQueryPageParams));


        return page;
    }

    @Override
    public String queryNewRejectReason() {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long id = currentUser.getId();
       //查询拒绝原因表来查询最新的拒绝原因
        LambdaQueryWrapper<RejectReason> rejectReasonLambdaQueryWrapper = Wrappers.<RejectReason>lambdaQuery()
                .eq(RejectReason::getWorkInstitutionId, id)
                .orderByAsc(RejectReason::getCertificationTime);
        List<RejectReason> rejectReasons = rejectReasonMapper.selectList(rejectReasonLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(rejectReasons)) {
            return rejectReasons.get(0).getRejectReason();
        }
        return "";
    }

    @Override
    public void auditWork(Long id, AuditWorkReqDto auditWorkReqDto) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long auditorId = currentUser.getId();
        String auditorName = currentUser.getName();
        //获取审核状态
        int certificationStatus = auditWorkReqDto.getCertificationStatus();
        //判断审核状态
          //如果审核失败 就更新审核状态表和新建拒绝原因表
        if (certificationStatus == CertificationStatusEnum.FAIL.getStatus()) {
           //根据id更新审核状态表
            WorkerCertification workerCertification = baseMapper.selectById(id);
            workerCertification.setCertificationStatus(auditWorkReqDto.getCertificationStatus());
            workerCertification.setCertificationTime(LocalDateTime.now());
            updateById(workerCertification);
            //根据拒绝原因创建表
            LambdaQueryWrapper<RejectReason> eq = Wrappers.<RejectReason>lambdaQuery().eq(RejectReason::getWorkInstitutionId, id).eq(RejectReason::getAuditStatus, 0);
            RejectReason rejectReason = rejectReasonMapper.selectOne(eq);
            Long id1 = rejectReason.getId();
            BeanUtil.copyProperties(workerCertification, rejectReason);
            //设置服务人员id
            rejectReason.setId(id1);
            rejectReason.setWorkInstitutionId(id);
            //设置拒绝原因
            rejectReason.setRejectReason(auditWorkReqDto.getRejectReason());
            //审核状态为1已经审核
            rejectReason.setAuditStatus(1);
            //设置审核人id
            rejectReason.setAuditorId(auditorId);
           //设置审核人姓名
            rejectReason.setAuditorName(auditorName);
            rejectReasonMapper.updateById(rejectReason);
        }
        //如果审核通过就更新审核状态表
        else {
            WorkerCertification workerCertification = baseMapper.selectById(id);
            workerCertification.setCertificationStatus(auditWorkReqDto.getCertificationStatus());
            workerCertification.setCertificationTime(LocalDateTime.now());
            updateById(workerCertification);
            LambdaQueryWrapper<RejectReason> eq = Wrappers.<RejectReason>lambdaQuery().eq(RejectReason::getWorkInstitutionId, id).eq(RejectReason::getAuditStatus, 0);
            RejectReason rejectReason = rejectReasonMapper.selectOne(eq);
            Long id1 = rejectReason.getId();
            BeanUtil.copyProperties(workerCertification, rejectReason);
            rejectReason.setId(id1);
            //设置服务人员id
            rejectReason.setWorkInstitutionId(id);
            //审核状态为1已经审核
            rejectReason.setAuditStatus(1);
            //设置审核人id
            rejectReason.setAuditorId(auditorId);
            //设置审核人姓名
            rejectReason.setAuditorName(auditorName);
            rejectReasonMapper.updateById(rejectReason);
        }
    }
}
